<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\Cashier;

use AuctionBack\Logic\CarReportLogic;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\System\SystemLog;
use Think\Log;

class Payment extends Cashier
{
    protected $payment_id = null;

    public function __construct($payment_id)
    {
        $this->model = M("payment");
        $this->payment_id = intval($payment_id);
    }

    /**
     * 新增付款
     * @param array $data
     *  int $pay_type 付款类型
     *  int $pay_way 付款方式
     *  int $amount 付款金额
     *  string $create_time 创建时间
     *  string $card_no 银行卡号
     *  string $bank_name 开户行
     *  string $account_name 账户名
     * @return mixed
     */
    public static function add($data)
    {
        $payment_no = genBillsNo("FK", $data['pay_type']);
        $data = [
            'payment_no' => $payment_no,
            'status' => $data['status'],
            'pay_type' => $data['pay_type'],
            'pay_way' => $data['pay_way'],
            'emp_id' => $data['emp_id'],
            'emp_name' => $data['emp_name'],
            'amount' => $data['amount'],
            'card_no' => $data['card_no'],
            'bank_name' => $data['bank_name'],
            'account_name' => $data['account_name'],
            'create_time' => $data['create_time'],
            'update_time' => $data['update_time'],
            'refer' => $data['refer'],
	        'branch_id' => $data['branch_id'],
        ];
        return M("payment")->add($data);
    }

    /**
     * 获取付款信息
     * @return mixed
     */
    public function getInfo()
    {
        if ($this->payment_id < 1) return false;
        return $this->model->where(['id' => $this->payment_id])->find();
    }

    /**
     * 更新付款信息
     * @param $data
     * @return bool
     */
    public function update($data)
    {
        if ($this->payment_id < 1) return false;
        //TODO 数据过滤
        return $this->model->where(['id' => $this->payment_id])->save($data);
    }

    /**
     * 锁定收款单
     * @param $id
     * @param int $emp_id
     * @param string $emp_name
     * @return bool
     */
    public static function lock($id, $emp_id = 0, $emp_name = '系统')
    {
        if (intval($id) < 1) return false;
        $info = self::getInfoById($id);
        if (empty($info)) return false;
        if ($info['status'] == 1) {
            return true;
        } elseif ($info['status'] == 2 || $info['status'] == 3) {
            return false;
        } else {
            $data = [
                'status' => 2,
                'emp_id' => $emp_id,
                'emp_name' => $emp_name,
                'update_time' => date('Y-m-d H:i:s'),
            ];
            return M("payment")->where(['id' => $id])->save($data);
        }
    }

    /**
     * 解锁收款单
     * @param $id
     * @param int $emp_id
     * @param string $emp_name
     * @return bool
     */
    public static function unlock($id, $emp_id = 0, $emp_name = '系统')
    {
        if (intval($id) < 1) return false;
        $info = self::getInfoById($id);
        if (empty($info)) return false;
        if ($info['status'] == 1 || $info['status'] == 0) { //如果是未付或者已付时，直接返回解锁成功
            return true;
        } elseif ($info['status'] == 3) {
            return false;
        } else {
            $data = [
                'status' => 0,
                'emp_id' => $emp_id,
                'emp_name' => $emp_name,
                'update_time' => date('Y-m-d H:i:s'),
            ];
            return M("payment")->where(['id' => $id])->save($data);
        }
    }

    /**
     * 作废收款单
     * @param $id
     * @return bool
     */
    public static function invalid($id)
    {
        if (intval($id) < 1) return false;
        return M('payment')->where(['id' => $id])->save(['status' => 3]);
    }

    /**
     * 获取付款单(复数)实收金额
     * @param array $ids 付款的ID
     * @return array|bool
     */
    public static function getPaymentByIds($ids = array())
    {
        if (empty($ids)) return false;
        $map = [];
        $map['id'] = ['in', $ids];
        $map['status'] = 1;
        $Payment = M('payment');
        $sumAmount = $Payment->where($map)->sum('amount');
        $data = [];
        $data['amount'] = $sumAmount;
        $data['status'] = $sumAmount > 0 ? 1 : 0;
        return $data;
    }

    /**
     * 付款列表
     * @param int $page
     * @param int $limit
     * @param array $params
     * @return array
     */
    public static function getList($page = 1, $limit = 10, $params = array())
    {
        $data = [];
        $page = intval($page) > 0 ? intval($page) : 1;
        $limit = intval($limit) > 0 ? intval($limit) : 10;
        $map = [];
        $map['status'] = intval($params['status']);
        //
        $order = "create_time ASC ";
        if ($params['status'] > 0) {
            $order = "update_time DESC";
        }

        $ids = [];
        $sid = 0;
//        if(!empty($params['plate_number'])){
//            $plate_prefix = mb_substr($params['plate_number'], 0, 1, 'UTF8');
//            $plate_prefix = array_search($plate_prefix,C('PLATE_PREFIX'));
//            if($plate_prefix == false){
//                return $data;
//            }
//            $plate_suffix = mb_substr($params['plate_number'], 1, 7, 'UTF8');
//            $carMap = [
//                'prefix' => $plate_prefix,
//                'suffix' => $plate_suffix,
//            ];
//            $carInfo = CarReportLogic::getCarByPlateNo($carMap);
//            $sid = $carInfo['sid'];
//        }

        //车辆编号
        if (!empty($params['car_no'])){
            $sid = M("cars")->field('car_id')->where(['sno' => $params['car_no']])->getField("sid");
        }
        //转换成车源ID
        if($sid > 0){
            $paymentIds = self::getPaymentsIdBySid($sid);
          if (empty($paymentIds)) return $data;
            $ids = array_merge($ids, $paymentIds);
        }
        if (!empty($ids)) {
            $ids = array_unique($ids);
            $map['id'] = ['in', $ids];
        }
        //付款编号
        if (!empty($params['payment_no'])) {
            $map['payment_no'] = $params['payment_no'];
        }
        //付款类型
        if ($params['pay_type'] > 0) {
            $map['pay_type'] = intval($params['pay_type']);
        }
        //分公司
        if($params['branch_id'] > -1){
            $map['branch_id'] = intval($params['branch_id']);
        }
        $m = M("payment");
        $total = $m->where($map)->count();
        $list = $m->where($map)->page($page)->order($order)->limit($limit)->select();
        if (!empty($list)) {
            foreach ($list as $key => $item) {
                if (in_array($item['pay_type'], [1, 2, 3])) {
                    $info = self::getPurchaseInfoById($item['id']);
                    $list[$key]['order_no'] = $info['order_no'];
                    $list[$key]['sid'] = $info['sid'];
                    $list[$key]['car_source_nu'] = $info['car_source_nu'];
                    $list[$key]['purchase_order_nu'] = $info['purchase_order_nu'];
                    $list[$key]['account_id'] = $info['owner_id'];
                    $list[$key]['account_name'] = $info['owner_name'];
                    $list[$key]['account_type'] = "车主";
                    $list[$key]['modify_no'] = "--";
                } elseif (in_array($item['pay_type'], [4, 5, 6, 7])) {
                    if ($item['refer'] > 0) {
                        $info = self::getCarBackInfoByPaymentId($item['id']);
                        $list[$key]['modify_no'] = "--";
                    } else {
                        $info = self::getChangeInfoById($item['id']);
                        $list[$key]['modify_no'] = $info['modify_no'];
                    }

                    if ($item['pay_type'] == 6) {
                        $list[$key]['account_id'] = $info['owner_id'];
                        $list[$key]['account_name'] = $info['owner_name'];
                        $list[$key]['account_type'] = "车主";
                    } else {
                        $list[$key]['account_id'] = $info['success_dealer_id'];
                        $list[$key]['account_name'] = $info['dealer_name'];
                        $list[$key]['account_type'] = "车商";
                    }
                    $list[$key]['order_no'] = $info['order_no'];
                    $list[$key]['car_source_nu'] = $info['car_source_nu'];
                    $list[$key]['purchase_order_nu'] = $info['purchase_order_nu'];
                } elseif ($item['pay_type'] == 8) { //保证金提取
                    $info = self::getBailInfoByPaymentId($item['id']);
                    //dump($info);
                    $list[$key]['order_no'] = '--';
                    $list[$key]['car_source_nu'] = '--';
                    $list[$key]['account_id'] = $info['dealer_id'];
                    $list[$key]['account_name'] = $info['contact_person'];
                    $list[$key]['account_type'] = "车商";
                }

                if ($item['status'] > 1) {
                    $list[$key]['emp_name'] = empty($item['emp_name']) ? "系统" : $item['emp_name'];
                }
            }
        }
        $data['total'] = $total;
        $data['list'] = $list;
        return $data;
    }

    /**
     * 获取采购单信息
     * @param $id
     * @return mixed
     */
    public static function getPurchaseInfoById($id)
    {
        $map = [];
        $map['pp.payment_id'] = intval($id);
        $prefix = C("DB_PREFIX");
        $info = M('purchase_payments')->alias('pp')->field('po.purchase_order_nu,po.order_no,c.sid,c.sno as car_source_nu,po.amount AS should_pay,c.owner_id,co.seller_name as owner_name')
            ->join($prefix . "purchase_order AS po ON pp.po_id=po.id")
            ->join($prefix . "cars AS c ON po.car_id=c.car_id")
            ->join($prefix . "car_owner AS co ON c.owner_id=co.owner_id")
            ->where($map)->find();
        return $info;
    }

    /**
     * 获取变更单信息
     * @param $id
     * @return mixed
     */
    public static function getChangeInfoById($id)
    {
        $map = [];
        $map['cp.payment_id'] = intval($id);
        $prefix = C("DB_PREFIX");
        $cols = "ml.*,po.purchase_order_nu,po.amount AS should_pay,o.order_no,c.car_id,c.sno as car_source_nu,c.owner_id,co.seller_name as owner_name,o.success_dealer_id,cd.contact_person as dealer_name";
        $info = M('change_payment')->alias('cp')->field($cols)
            ->join($prefix . "modify_list AS ml ON cp.change_id=ml.mid")
            ->join($prefix . "order AS o ON ml.order_id=o.order_id")
            ->join($prefix . "car_dealer AS cd ON o.success_dealer_id=cd.dealer_id")
            ->join($prefix . "purchase_order AS po ON ml.po_id=po.id")
            ->join($prefix . "cars AS c ON po.car_id=c.car_id")
            ->join($prefix . "car_owner AS co ON c.owner_id=co.owner_id")
            ->where($map)->find();
        return $info;
    }

    /**
     * 获取退车信息
     * @param int $paymentId
     * @param string $table
     * @return mixed
     */
    public static function getCarBackInfoByPaymentId($paymentId)
    {
        $map = [];
        $map['bc.payment_id'] = intval($paymentId);
        $prefix = C("DB_PREFIX");
        $cols = "c.sno as car_source_nu,bc.car_id,c.owner_id,co.seller_name as owner_name,o.order_no,po.purchase_order_nu";
        $info = M('refund_car')->alias("bc")->field($cols)
            ->join($prefix . "cars AS c ON c.car_id=bc.car_id")
            ->join($prefix . "car_owner AS co ON c.owner_id=co.owner_id")
            ->join($prefix . "order AS o ON c.car_id=o.car_id")
            ->join($prefix . "purchase_order AS po ON bc.sid=po.sid")
            ->where($map)
            ->find();
        return $info;
    }


    /**
     * 获取保证金充值信息
     * @param $payment_id
     * @return mixed
     */
    public static function getBailInfoByPaymentId($payment_id)
    {
        $map = [
            'use_type' => 4,
           'payment_id' => $payment_id,
        ];
        $bailInfo = M("dealer_bail_log")->where($map)->find();
        return M("car_dealer")->where(['dealer_id' => $bailInfo['dealer_id']])->find();
    }

    /**
     * 通过id获信息
     * @param $id
     * @return mixed
     */
    public static function getInfoById($id)
    {
        return M("payment")->where(['id' => $id])->find();
    }

    /**
     * 是否有未付款单
     * @param $ids
     * @return bool
     */
    public static function checkStatusByIds($ids)
    {
        if (!is_array($ids)) return false;
        $map = [];
        $map['id'] = ['in', $ids];
        $map['status'] = 0; //未付款
        $list = M("payment")->where($map)->select();
        if (!empty($list)) {
            return false;
        }
        return true;
    }


    public function confirmPayment($data)
    {
        $paymentData = [
            'emp_id' => $data['emp_id'],
            'emp_name' => $data['emp_name'],
            'status' => $data['status'],
            'update_time' => $data['update_time'],
        ];
        //更新付款信息
        M()->startTrans();
        $resPayment = $this->update($paymentData);
        if (!$resPayment) {
            M()->rollback();
            Log::record("确认付款，更新付款信息失败，付款ID： [ {$this->payment_id} ] ");
            return false;
        }
        $res = true;
        if (in_array($data['pay_type'], [1, 2, 3])) {
            //采购单处理
            $res = $this->purchaseOrderConfirm($data);
        } elseif ($data['refer'] == 0 && in_array($data['pay_type'], [4, 5, 6, 7])) {
            //变更单处理
            $res = $this->changeOrderConfirm();
        }
        if (!$res) {
            M()->rollback();
            return false;
        }
        //事务提交
        M()->commit();
        //记录操作日志
        SystemLog::add([
            'emp_id' => $data['emp_id'],
            'order_id' => $this->payment_id,
            'car_id' => 0,
            'owner_id' => 0,
            'action' => '确认付首款'
        ]);
        return true;
    }

    /**
     * 采购单确认
     * @param $data
     * @return bool
     */
    private function purchaseOrderConfirm($data)
    {
        //找到采购单ID
        $poId = M("purchase_payments")->where(['payment_id' => $this->payment_id])->getField('po_id');
        $po = new PurchaseOrder($poId);
        $res = $po->paymentCallback($data['pay_type'], $data['emp_id']);
        return $res;
    }

    /**
     * 变更单确认
     * @return bool
     */
    private function changeOrderConfirm()
    {
        //找到变更单信息
        $mid = M("change_payment")->where(['payment_id' => $this->payment_id])->getField("change_id");
        $co = new ChangeOrder($mid);
        $changeOrderInfo = $co->detail();
        if (empty($changeOrderInfo)) {
            Log::record("变更单信息不存在");
            return false;
        }
        //变更单回调
        $res = $co->cashierCallback();
        return $res;
    }


    /**
     * 根据变更单ID修改付款单状态
     * @param $mid
     * @return bool
     */
    public static function changeStatusByMid($mid)
    {
        $prefix = C("DB_PREFIX");
        $map = [];
        $map['cp.change_id'] = $mid;
        $map['p.status'] = '-1';
        $payment_id = M('change_payment')->alias('cp')->field('p.id')
            ->join($prefix . "payment AS p ON p.id=cp.payment_id")
            ->where($map)->find();
        if ($payment_id) {
            return $res = M('payment')->where(['id' => $payment_id['id']])->save(['status' => 0]);
        } else {
            return true;
        }
    }

    /**
     * 根据SID获取付款信息
     * @param $sid
     * @return array
     */
    public static function getPaymentsIdBySid($sid)
    {
        //采购应付
        $purchasePaymentIds = self::getPurchasePaymentIdBySid($sid);
        //变更单付款单
        $changePaymentIds = self::getChangePaymentIdsBySid($sid);

        $paymentIds = array_merge($purchasePaymentIds,$changePaymentIds);
        $breachCarInfo = M("breach_car")->where(['sid'=>$sid,'status'=>2])->find();
        if(!empty($breachCarInfo)){
            $paymentIds[] = $breachCarInfo['payment_id'];
        }
        $selfReceiveCar = M("self_receive_car")->where(['sid'=>$sid,'status'=>2])->find();
        if(!empty($selfReceiveCar)){
            $paymentIds[] = $selfReceiveCar['payment_id'];
        }
        return $paymentIds;
    }

    /**
     * 根据变更单ID获取付款单信息
     * @param $mid
     * @return bool|mixed
     */
    public static function getPaymentByMid($mid)
    {
        if ($mid < 1) return false;
        $paymentId = M("change_payment")->where(['change_id' => $mid])->getField("payment_id");
        $where = [
            'id' => $paymentId,
            'status' => ['in', [0, 1]] //未付或者锁定的付款单
        ];
        return M("payment")->where($where)->find();
    }

    /**
     * @param $sid
     * @return array|bool
     */
    private static function getChangePaymentIdsBySid($sid)
    {
        if($sid<1) return false;
        $paymentsId = [];
        $changeOrders = M("modify_list")->where(['sid'=>$sid])->select();
        $changeOrderIds = [];
        foreach ($changeOrders as $co){
            $changeOrderIds[] = $co['mid'];
        }

        if(!empty($changeOrderIds)){
            $where = [
                'change_id' => ['in',$changeOrderIds]
            ];
            $payments = M("change_payment")->where($where)->select();
            foreach ($payments as $pay){
                $paymentsId[] = $pay['payment_id'];
            }
        }
        return $paymentsId;
    }

    /**
     * 根据SID获取采购应付的付款单
     * @param $sid
     * @return array|bool
     */
    private static function getPurchasePaymentIdBySid($sid)
    {
        if($sid<1) return false;
        $paymentsId = [];
        $po = new PurchaseOrder();
        $purchaseOrder = $po->viewBySid($sid);
        if(!empty($purchaseOrder)){
            $list = M("purchase_payments")->where(['po_id'=>$purchaseOrder['id']])->select();
            foreach ($list as $item){
                $paymentsId[] = $item['payment_id'];
            }
        }
        return $paymentsId;
    }


}